package com.kaihui.module_web.ui.web

import android.app.backup.BackupHelper
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.View
import android.webkit.DownloadListener
import android.webkit.ValueCallback
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog

import androidx.localbroadcastmanager.content.LocalBroadcastManager
import cn.org.bjca.signet.component.core.bean.results.SignetBaseResult
import cn.org.bjca.unifysdk.coss.CossApi
import cn.org.bjca.unifysdk.signet.SignetApi
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.kaihui.lib_base.base.BaseVMBActivity
import com.kaihui.lib_base.data.bean.Article
import com.kaihui.lib_base.data.bean.Banner
import com.kaihui.lib_base.data.bean.CollectArticle
import com.kaihui.lib_base.data.bean.CollectUrl
import com.kaihui.lib_base.data.bean.DownloadBean
import com.kaihui.lib_base.data.bean.MimeTyppes
import com.kaihui.lib_base.data.local.IpManager
import com.kaihui.lib_base.export.ModuleWebApi
import com.kaihui.lib_base.ext.initClose
import com.kaihui.lib_base.ext.initTitle
import com.kaihui.lib_base.utils.DownloadService
import com.kaihui.lib_base.utils.LogUtil
import com.kaihui.lib_base.utils.ToastUtil
import com.kaihui.module_web.R
import com.kaihui.module_web.data.DeviceInfo
import com.kaihui.module_web.databinding.WebActivityWebBinding
import com.kaihui.module_web.jsinterface.AgentWebBackHelper
import com.kaihui.module_web.jsinterface.AndroidInterface
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import androidx.core.net.toUri
import kotlinx.coroutines.MainScope


/**
 * WebView，用的第三方更强大的agentWeb
 *
 * @author LTP 2022/4/2
 */
@Route(path = ModuleWebApi.ROUTER_WEB_WEB_ACTIVITY)
class WebActivity :
    BaseVMBActivity<WebViewModel, WebActivityWebBinding>(R.layout.web_activity_web) {
    companion object {
        //控制两种打开方式
        val TAKE_PHOTO = 1000
        val CHOOSE_PHOTO = 2000
        val CHOOSER_REQUEST_OA = 3000

        val DEFAULT_IP_ADDRESS_REMOTE = "https://dev-mb.isignet.cn:8080/MSSPServer/"
        val APP_ID = "67f6c99b74484c2b8bcb35473850cdd7"
    }


    var imageUri: Uri? = null
    var cossApi: CossApi? = null
    var signetApi: SignetApi? = null
    var signetBaseResult: SignetBaseResult? = null
    val mainHandler = Handler(Looper.getMainLooper())
    val scope = MainScope()
    private lateinit var mAgentWeb: AgentWeb

    @Autowired(name = ModuleWebApi.ROUTER_WEB_EXTRA_ARTICLE)
    @JvmField
    var mArticle: Article? = null

    @Autowired(name = ModuleWebApi.ROUTER_WEB_EXTRA_COLLECT_ARTICLE)
    @JvmField
    var mCollectArticle: CollectArticle? = null

    @Autowired(name = ModuleWebApi.ROUTER_WEB_EXTRA_COLLECT_URL)
    @JvmField
    var mCollectUrl: CollectUrl? = null

    @Autowired(name = ModuleWebApi.ROUTER_WEB_EXTRA_BANNER)
    @JvmField
    var mBanner: Banner? = null
    val BASE_URL = IpManager.getDefaultHomePage()
    var backHelper: AgentWebBackHelper?=null
    private lateinit var mUrl: String
    private var mCollect = false
    private lateinit var mTitle: String
    private var androidInterface: AndroidInterface? = null

    var uploadMessage: ValueCallback<Uri>? = null //单选文件回调


    var uploadMessageAboveL: ValueCallback<Array<Uri>>? = null //多选文件回调
    private var dialog: AlertDialog? = null

    private val mWebViewClient = object : WebViewClient() {
        private var timeoutHandler = Handler(Looper.getMainLooper())
        private var timeoutRunnable: Runnable? = null
        private val TIMEOUT_DURATION = 10L // 10秒超时

        override fun onPageStarted(view: android.webkit.WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            LogUtil.e("error----onPageStarted:view?.progress=="+view?.progress)

        }

        override fun onPageFinished(view: android.webkit.WebView?, url: String?) {
            super.onPageFinished(view, url)
            // 页面加载完成，清除超时任务
            timeoutRunnable?.let { timeoutHandler.removeCallbacks(it) }
        }

        override fun onReceivedError(
            view: android.webkit.WebView?,
            request: WebResourceRequest?,
            error: WebResourceError?
        ) {
            super.onReceivedError(view, request, error)
            LogUtil.e("error----onReceivedError:error==errorCode="+error?.errorCode+" description="+error?.description)
            // 处理错误
            if (error?.errorCode == ERROR_TIMEOUT) {
                loadErrorPage(view)
            }
        }

        override fun onReceivedHttpError(
            view: android.webkit.WebView?,
            request: WebResourceRequest?,
            errorResponse: WebResourceResponse?
        ) {
            super.onReceivedHttpError(view, request, errorResponse)
            LogUtil.e("error----onReceivedHttpError:errorResponse==$errorResponse")
//            if (errorResponse?.statusCode ?: 0 >= 400) {
//                loadErrorPage(view)
//            }
        }

        private fun loadErrorPage(webView: android.webkit.WebView?) {
            webView?.loadUrl("file:///android_asset/error.html")
        }
    }
    private val mWebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: android.webkit.WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            // 可以在这里处理进度变化
            LogUtil.e("加载进度newProgress==$newProgress")
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            mTitle = title ?: ""
        }

        override fun onShowFileChooser(
            webView: WebView?,
            filePathCallback: ValueCallback<Array<Uri>>?,
            fileChooserParams: FileChooserParams?,
        ): Boolean {
            uploadMessageAboveL = filePathCallback

            startActivityForResult(
                Intent.createChooser(
                    getFilerChooserIntent(
                        fileChooserParams!!.acceptTypes[0]
                    ), "File Chooser"
                ), CHOOSER_REQUEST_OA
            )

            return true;

        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        // 自动完成参数注入
        ARouter.getInstance().inject(this@WebActivity)
        XXPermissions.with(this@WebActivity)
            // 申请单个权限
            .permission(
                Permission.CAMERA,
                Permission.MANAGE_EXTERNAL_STORAGE
            )
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        LogUtil.e("获取部分权限成功，但部分权限未正常授予")
                        ToastUtil.showShort(
                            applicationContext,
                            "获取部分权限成功，但部分权限未正常授予"
                        )
                        return
                    }

                    LogUtil.e("获取拍照和存储权限成功")
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        LogUtil.e("被永久拒绝授权，请手动授予拍照和存储权限")
                        ToastUtil.showShort(
                            applicationContext,
                            "被永久拒绝授权，请手动授予拍照和存储权限"
                        )
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@WebActivity, permissions)
                    } else {
                        LogUtil.e("获取拍照和存储权限失败")
                        ToastUtil.showShort(applicationContext, "获取拍照和存储权限失败")
                    }
                }
            })
        cossApi = CossApi.getInstance(application, DEFAULT_IP_ADDRESS_REMOTE, APP_ID)

        signetApi = SignetApi.getInstance(application)

        mBinding.toolbar.apply {
            setSupportActionBar(this)
            initTitle("加载中...")
            initClose { onBackPressed() }
        }

        when {
            mArticle != null -> {
                mUrl = mArticle!!.link
                mCollect = mArticle!!.collect
            }

            mCollectArticle != null -> {
                mUrl = mCollectArticle!!.link
                mCollect = true
            }

            mCollectUrl != null -> {
                mUrl = mCollectUrl!!.link
                mCollect = true
            }

            else -> {
                mUrl = mBanner!!.url
                mCollect = false // 无法得知是否收藏直接置为false
            }
        }

        mAgentWeb = AgentWeb.with(this@WebActivity)
            .setAgentWebParent(mBinding.flWeb, FrameLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(mWebViewClient)
            .createAgentWeb()
            .ready()
            .go(mUrl)
        val settings = mAgentWeb.webCreator.webView.settings

        mAgentWeb.webCreator.webView.settings.textZoom = 100;
        mAgentWeb.webCreator.webView.settings.cacheMode = WebSettings.LOAD_DEFAULT
        mAgentWeb.webCreator.webView.settings.domStorageEnabled = true
        mAgentWeb.webCreator.webView.settings.databaseEnabled = true
        mAgentWeb.webCreator.webView.settings.useWideViewPort = true//關鍵點
        mAgentWeb.webCreator.webView.settings.loadWithOverviewMode = true
        mAgentWeb.webCreator.webView.settings.layoutAlgorithm =
            WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
        mAgentWeb.webCreator.webView.settings.builtInZoomControls = true
        mAgentWeb.webCreator.webView.settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        mAgentWeb.webCreator.webView.settings.setJavaScriptEnabled(true)

        mAgentWeb.webCreator.webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
        mAgentWeb.webCreator.webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            LogUtil.e("HEHE", "开始下载:" + url)
            val downloadBean = Gson().fromJson(url, DownloadBean::class.java)
            downLoadFile(downloadBean)
        })
        LocalBroadcastManager.getInstance(applicationContext).registerReceiver(
            downloadReceiver, IntentFilter("com.example.DOWNLOAD_COMPLETE")
        )
        registerAction()
        androidInterface = AndroidInterface(mAgentWeb, this@WebActivity)
        mBinding.btTest.setOnClickListener {
            val servUrl = "http://dev.isignet.cn:8080/MSSPServer/"
            val appId = "67f6c99b74484c2b8bcb35473850cdd7"
            androidInterface?.initConfig(servUrl,appId)
            androidInterface?.qrReqCert("12345")
            LogUtil.e("signetBaseResult==${signetBaseResult}")
        }
        backHelper = AgentWebBackHelper(mAgentWeb)
        LogUtil.e("mUrl==${mUrl}")
        val deviceInfo = getDeviceInfoSync();
        LogUtil.e("deviceInfo:$deviceInfo")
    }

    private fun registerAction() {
        mAgentWeb.jsInterfaceHolder.addJavaObject(
            "signet",
            AndroidInterface(mAgentWeb, this@WebActivity)
        )
    }

    fun getDeviceInfoSync(): DeviceInfo {
        return try {
            val contentResolver = this.contentResolver
            val uri = "content://com.newmobiler.portal.provider.mdmsdk".toUri()
            val bundle = Bundle().apply {
                putString("pkg", "com.zf.bg")
            }

            val result = contentResolver.call(uri, "deviceInfoV2", "info", bundle)

            if (result != null) {
                DeviceInfo(
                    userName = result.getString("userName") ?: "",
                    phoneNum = result.getString("phoneNum") ?: "",
                    idNumber = result.getString("idNumber") ?: "",
                    imei = result.getString("imei") ?: "",
                    imsi = result.getString("imsi") ?: "",
                    iccid = result.getString("iccid") ?: ""
                )
            } else {
                DeviceInfo("","","","","","")
            }
        } catch (e: Exception) {
            LogUtil.e("DeviceInfo", "Error: ${e.message}")
            DeviceInfo("","","","","","")
        }
    }

    /**
     * 返回主页
     */
    fun goHome() {
        mAgentWeb.urlLoader.loadUrl(BASE_URL)
    }

    /**
     * 重写返回键处理
     */
    override fun onBackPressed() {
        if (backHelper?.handleBackPress(this) == false) {
            super.onBackPressed()
        }
    }

    override fun onResume() {
        mAgentWeb.webLifeCycle.onResume()
        super.onResume()

    }

    override fun onPause() {
        mAgentWeb.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        mAgentWeb.webLifeCycle.onDestroy()
        super.onDestroy()
    }

    fun downLoadFile(downloadBean: DownloadBean) {

        val downloadService = DownloadService()
        val mediaStorageDir = File(
            Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS
            ), "kaihui"
        )
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                LogUtil.e("failed to create directory")
            }
        }
        val mediaFile = File(
            mediaStorageDir.path + File.separator +
                    downloadBean.name
        )
        val filePath = mediaFile.path

        CoroutineScope(Dispatchers.Main).launch {
            downloadService.downloadFile(applicationContext, downloadBean.url, filePath)
        }
    }

    fun getFilerChooserIntent(flag: String): Intent {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)

        intent.addCategory(Intent.CATEGORY_OPENABLE)
        when (flag) {
            ".jpg" -> {
                intent.type = "image/*"

            }

            ".xls" -> {
                intent.putExtra(
                    Intent.EXTRA_MIME_TYPES,
                    arrayOf(MimeTyppes.XLS, MimeTyppes.XLST, MimeTyppes.XLSX)
                )

                intent.type = "*/*"

            }

            ".pdf" -> {
                intent.type = "application/pdf"

            }

            ".doc" -> {

                intent.putExtra(
                    Intent.EXTRA_MIME_TYPES,
                    arrayOf(MimeTyppes.DOC, MimeTyppes.DOCX, MimeTyppes.DOTX)
                )
                intent.type = "*/*"

            }

            else -> {
                intent.type = "*/*"

            }
        }
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
        return intent
    }

    private val downloadReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val filePath = intent.getStringExtra("filePath")
            val intent = Intent()
            val uri = Uri.fromFile(File(filePath))
            intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) //表示要将数据添加进系统的媒体资源库
            intent.setData(uri) //将照片文件的地址存入数据库
            applicationContext.sendBroadcast(intent)

            LogUtil.e("下载完成")
            ToastUtil.showShort(applicationContext, "下载完成")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            TAKE_PHOTO -> if (resultCode == RESULT_OK) {
                try {
                    LogUtil.e("相机返回:imageUri==${imageUri}")
                    val intent = Intent()
                    intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) //表示要将数据添加进系统的媒体资源库
                    intent.setData(imageUri) //将照片文件的地址存入数据库
                    sendBroadcast(intent)
                    // 将拍摄的照片显示出来
                    val bitmap =
                        BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri!!))

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            CHOOSE_PHOTO -> if (resultCode == RESULT_OK) {
                LogUtil.e("相册返回")
                val inputStream = contentResolver.openInputStream(data!!.data!!)
                val bitmap = BitmapFactory.decodeStream(inputStream)

            }

            CHOOSER_REQUEST_OA -> if (resultCode == RESULT_OK) {
                if (null == uploadMessageAboveL) return
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveLOA(requestCode, resultCode, data)
                }
            }
        }
    }

    private fun onActivityResultAboveLOA(requestCode: Int, resultCode: Int, intent: Intent?) {
        if (uploadMessageAboveL == null) return
        var results: Array<Uri>? = null
        if (resultCode == RESULT_OK) {
            if (intent != null) {
                val dataString = intent.dataString
                if (dataString != null) results = arrayOf(Uri.parse(dataString))
            }
        }
        uploadMessageAboveL!!.onReceiveValue(results)
        uploadMessageAboveL = null
    }
}
